#!/usr/bin/python3
#
# Init script skeleton for Python-based service control scripts
#
# chkconfig: 123456 1 99
# description: My service
#
# Author: Josh Johnson
# Last Author: Aydin Demirel: aydin@demirel.web.tr - 2018
#
### BEGIN INIT INFO
# Provides: my-service
# Required-Start:
# Required-Stop:
# Default-Start:  123456
# Default-Stop:  123456
# Short-Description: My service
# Description: My service
### END INIT INFO


import sys, os, subprocess, re, time

def servisIsleme(self,servis_adi,komut):

    servis_adi = sys.argv[1].lower()
    komut = sys.argv[2].lower()

    if komut == 'start':
        servisBaslat(servis_adi)
    elif komut == 'stop':
        servisDurdur(servis_adi)
    elif komut == 'restart':
        servisYenidenBaslat(servis_adi)
    elif komut == 'status':
        servisDurumu(servis_adi)
    else:
        sys.exit('Bilinmeyen komut: "%s".' % komut)

def kilitle(servisAdi):
    """
    Create the /var/lock/subsys file
    """
    open('/var/run/lock/%s' % servisAdi, 'w').close()


def kilitDurumu(servis_adi):
    """
    Return True if the lock file exists
    """
    return os.path.exists('/var/run/lock/%s' % servis_adi)


def kilitAc(servis_adi):
    """
    Remove the /var/lock/subsys file
    """
    os.remove('/var/run/lock/%s' % servis_adi)


def servisBaslat(servis_adi):
    """
    Do whatever needs to be done.. this is where you start any applications,
    mount filesystems, etc.
    """
    subprocess.call("servis %s start" % servis_adi, stdout=subprocess.PIPE)


def servisDurdur(servis_adi):
    """
    Shut everything down, clean up.
    """
    subprocess.call("servis %s stop" % servis_adi, stdout=subprocess.PIPE)

def servisYenidenBaslat():
    """
    Stop and then start
    """
    servisDurdur()
    kilitle()
    servisBaslat()


def servisDurumu():
    """
    Print any relevant status info, and return a status code, an integer:

    0	      program is running or service is OK
    1	      program is dead and /var/run pid file exists
    2	      program is dead and /var/lock lock file exists
    3	      program is not running
    4	      program or service status is unknown
    5-99	  reserved for future LSB use
    100-149	  reserved for distribution use
    150-199	  reserved for application use
    200-254	  reserved

    @see: http://dev.linux-foundation.org/betaspecs/booksets/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
    """
    if not kilitDurumu():
        # this is dubious! if you're controlling another process, you should check its
        # PID file or use some other means.. consider this an example
        print("DURUM: Servis çalışmıyor")
        return 3
    else:
        print("DURUM: Servis çalışıyor")
        return 0


def test(servisAdi):
    """
    This is my way of "unit testing" the script. This function
    calls each of actions, mimicking the switchboard below.

    It then verifies that the functions did what they were supposed to,
    and reports any problems to stderr.

    """
    # Since this will turn off the system when its complete,
    # I want to warn the user and give them the chance to opt out if they
    # chose this option by accident.

    ok = input("""
******************
SERVİS TESTİ
******************

Bu tüm testlerden sonra srevisi KAPATACAK tır.

Bu sadece test ve hata ayıklama süreçleri için çalıştırılmalıdır.

Bunu yapmak istediğinize emin misiniz? [E/H]: """
                   ).lower()

    if ok != 'e':
        print >> sys.stderr, "İptal ediliyor..."
        return

    print("Kilit dosyası yazılıyor..")
    kilitle()
    print("Kilit dosyası doğrulanıyor...")
    if os.path.exists('/var/lock/subsys/my-service'):
        print("Kilit dosyası yazıldı...")
    else:
        print >> sys.stderr, "HATA: Kilit dosyası yazılamadı"

    print("Başlatılıyor...")
    servisBaslat()
    # Do stuff to check the start() function
    #
    #

    # we call status a couple of times so we can test if it's returning the right
    # output under different circumstances
    servisDurumu()

    print("Durduruluyor...")
    servisDurdur()
    # Do stuff to check the stop() function
    #
    #

    print("Kilit dosyası kaldırılıyor...")
    kilitAc()

    if os.path.exists('/var/run/lock/%s' % servisAdi):
        print >> sys.stderr, "HATA: Kilit dosyası kaldırılamadı"
    else:
        print("Kilit dosyası başarıyla kaldırıldı")

    # one more time to see what it looks like when the service off
    servisDurumu()


if __name__ == '__main__':
    try:
        # if there's fewer than 2 options on the command line
        # (sys.argv[0] is the program name)
        if len(sys.argv) == 1:
            raise ValueError;

        action = str(sys.argv[1]).strip().lower()

        if action == 'start':
            kilitle()
            servisBaslat()
            sys.exit(0)
        elif action == 'stop':
            servisDurdur()
            kilitAc()
            sys.exit(0)
        elif action == 'restart' or action == 'force-reload':
            servisYenidenBaslat()
            sys.exit(0)
        elif action == 'status':
            OK = servisDurumu()
            sys.exit(OK)
        elif action == 'test':
            test()
            sys.exit(0)
        else:
            raise ValueError

    except (SystemExit):
        # calls to sys.exit() raise this error :(
        pass
    except (ValueError):
        print >> sys.stderr, "Kullanım: servis_adi [start|stop|restart|force-reload|status|test]"
        # return 2 for "bad command line option"
        sys.exit(2)
    except:
        # all other exceptions get caught here
        extype, value = sys.exc_info()[:2]
        print >> sys.stderr, "HATA: %s (%s)" % (extype, value)
        # return 1 for "general error"
        sys.exit(1)
